
/// <reference path="../lib/types.d.ts" />

import utils = require('../lib/utils');
import service = require('../service/index');
import FileUtil = require('../lib/FileUtil');

import CompileProject = require('../actions/CompileProject');
import { publishResource, legacyPublishHTML5, legacyPublishNative } from '../actions/PublishResourceAction';
import ZipCommand = require("../actions/ZipCommand");
import * as EgretProject from '../project';
import * as path from 'path';



class Publish implements egret.Command {

    async execute(): Promise<number> {
        utils.checkEgret();

        const options = egret.args;
        const config = EgretProject.projectData;

        const target = egret.args.target;
        const version = getVersionInfo();
        options.releaseDir = FileUtil.joinPath(config.getReleaseRoot(), target, version);
        globals.log(1402, target, "");
        await publishResource(version);
        return global.exitCode;
    }
}

function getVersionInfo() {
    if (egret.args.version) {
        return egret.args.version;
    }

    let filePath = EgretProject.projectData.getProjectRoot()+"version.txt";
    let str = FileUtil.read(filePath);
    let versionJson : any = {}
    if(str != ""){
        versionJson = JSON.parse(str);
        // console.log("@@@@@@@@@@@@@@@@@@@" + str,versionJson,versionJson[EgretProject.projectData.getChannel()]);
        let versionStr : string = versionJson[EgretProject.projectData.getChannel()];
        if(versionStr != "" && versionStr != null){
            var arr = versionStr.split(".");
            if(arr.length == 3){
                let newVersionStr = arr[0]+"."+arr[1]+"."+formatNum(parseInt(arr[2]) + 1);
                versionJson[EgretProject.projectData.getChannel()] = newVersionStr;
                FileUtil.writeFileAsync(filePath, JSON.stringify(versionJson),"utf-8");
                return versionStr;
            }else{
                console.log("渠道"+EgretProject.projectData.getChannel()+"配置错误")
            }
        }else{
            console.log("渠道"+EgretProject.projectData.getChannel()+"配置不存在")
        }
    }else{
        console.log(filePath,"文件不存在，或者内容为空，请检查配置")
    }

    versionJson[EgretProject.projectData.getChannel()] = "1.00.001"
    FileUtil.writeFileAsync(filePath, JSON.stringify(versionJson),"utf-8");

    return "1.00.001";
    // var date = new Date();
    // var year = date.getFullYear() % 100;
    // var month = date.getMonth() + 1;
    // var day = date.getDate();
    // var hour = date.getHours();
    // var min = date.getMinutes();
    // var second = date.getSeconds();
    // var timeStr = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + min * 100 + second;
    // return timeStr.toString();
}

function formatNum(val) : string{
    if(val > 100){
        return val;
    }
    if(val > 10){
        return "0" + val;
    }
    return "00" + val;
}


export = Publish;
